package com.javandad.app.server.mail.entity;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.jdo.PersistenceManager;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;

import com.javandad.app.server.db.DatabaseManager;
import com.javandad.app.server.db.PMFSingleton;
import com.javandad.app.shared.entity.Friendship;
import com.javandad.app.shared.entity.Mailable;
import com.javandad.app.shared.entity.User;

public class FInvitationMail extends JMail {
	public FInvitationMail(Friendship invi) {
		super(Session.getDefaultInstance(new Properties(), null));
		adapt(invi);
	}

	protected void adapt(Mailable a) {
		Friendship invi = (Friendship) a;
		try {
			this.setSubject(invi.getInviter() + " has added you as one of his/her friends!");
			String content = getContent(invi);
			this.setDataHandler(new DataHandler(new JMail.HTMLDataSource(content)));
			this.setFrom(new InternetAddress("javandad.info@gmail.com", "JaVandad"));
			PersistenceManager pm = PMFSingleton.getPM();
			DatabaseManager dbm = DatabaseManager.getDefaultDatabaseManager();
			User confirmer = dbm.getUser(invi.getConfirmer(), pm);
			this.addRecipient(RecipientType.TO, new InternetAddress(confirmer.getEmail()));
			pm.close();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}

	private String getContent(Friendship invi) {
		String c = "";

		c = "<table><tr><td>" + "You have been added by  " + invi.getInviter() + " at " + invi.getDateOfInvitation() + "</td></tr>" + "<tr><td><b>"
				+ "Click on the following link to get access to your notification box :" + "</b></td></tr><tr><td>" + "link : <a href='" + "" + "' >javandad.appspot.com</a>" + "</td></tr>"
				+ "</table>";

		return c;
	}

}
